package task3.util;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;
import javax.media.jai.PlanarImage;

public abstract class AbstractBean
  extends Panel
  implements Observer
{
  private static final long serialVersionUID = -38300556107816377L;
  protected BufferedImage _image;
  protected Vector<InputListener> _listeners;
  protected Label _textField;
  private ImageCanvas _imageField;
  
  public AbstractBean()
  {
    this._textField = new Label();
    this._imageField = new ImageCanvas();
    
    setLayout(new BorderLayout());
    add(this._textField, "North");
    add(this._imageField, "Center");
    
    this._listeners = new Vector();
  }
  
  public void update(Observable observable, Object object)
  {
    ImageTO image = (ImageTO)object;
    this._image = image.getEditedImage().getAsBufferedImage();
    this._imageField.repaint();
  }
  
  private BufferedImage getScaledImage(BufferedImage image, int width)
    throws IOException
  {
    int imageWidth = image.getWidth();
    
    double scale = width / imageWidth;
    AffineTransform scaleTransform = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, 2);
    
    return bilinearScaleOp.filter(image, new BufferedImage(width, width, image.getType()));
  }
  
  public abstract void run();
  
  private class ImageCanvas
    extends Canvas
  {
    private static final long serialVersionUID = -5951381589537500859L;
    
    public ImageCanvas()
    {
      setSize(100, 100);
    }
    
    public void paint(Graphics g)
    {
      super.paint(g);
      if (AbstractBean.this._image != null) {
        try
        {
          BufferedImage image = AbstractBean.this.getScaledImage(AbstractBean.this._image, getWidth());
          
          g.drawImage(image, 0, 0, null);
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
}
